package com.simen.hellobytes;

import com.simen.hellobytes.exception.ResNotFoundException;

import java.io.InputStream;
import java.net.URL;

/**
 * @author Created by Simen.
 * @date 创建日期 2018/10/25 17:02
 * @modify 修改者 Simen
 */
public class AssetsUtil {

    /**
     * 获取jar文件resources目录资源文件的输入流
     *
     * @param resFileName 资源文件名称
     * @return
     * @throws ResNotFoundException
     */
    public static InputStream openResInputStream(String resFileName) throws ResNotFoundException {
        ClassLoader classLoader = ClassLoader.getSystemClassLoader();

        InputStream inputStream = null;

        if (classLoader != null) {
            inputStream = classLoader.getResourceAsStream(resFileName);
        }

        if (inputStream == null) {
            classLoader = AssetsUtil.class.getClassLoader();

            if (classLoader != null) {
                inputStream = classLoader.getResourceAsStream(resFileName);
            }
        }

        if (inputStream == null) {
            inputStream = AssetsUtil.class.getResourceAsStream(resFileName.startsWith("/")?resFileName:("/"+resFileName));
        }

        if (inputStream == null) {
            throw new ResNotFoundException("not found resource file " + resFileName);
        }

        return inputStream;
    }

    public static URL openResUrl(String resFileName) throws ResNotFoundException {
        ClassLoader classLoader = ClassLoader.getSystemClassLoader();

        URL url = null;

        if (classLoader != null) {
            url = classLoader.getResource(resFileName);
        }

        if (url == null) {
            classLoader = AssetsUtil.class.getClassLoader();

            if (classLoader != null) {
                url = classLoader.getResource(resFileName);
            }
        }

        if (url == null) {
            url = AssetsUtil.class.getResource(resFileName.startsWith("/")?resFileName:("/"+resFileName));
        }

        if (url == null) {
            throw new ResNotFoundException("not found resource file " + resFileName);
        }

        return url;
    }

}
